var app = getApp();
// pages/discountMsg/discountMsg.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: `https://img.hn96606.com/images/activity/disMsg.png?${new Date()}`
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  loadMsg:function(e){
    wx.showModal({
      title: '',
      content: e,
      showCancel: false,
      success: function () {
      }
    })
  },

  tap:function(){
    let that = this;
    wx.request({
      url: app.serviceurl + 'Order/GetUserCoupon',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      dataType: 'json',
      success: function (res) {
        // IsCanUse：是否可用，使用次数限制
        if (!res.data.Result) {
          that.loadMsg('网络繁忙，请重新尝试')
          return 
        };
        if(res.data.UserCoupons != '' && res.data.UserCoupons != null && typeof(res.data.UserCoupons) != 'undefined'){
          wx.navigateTo({
            url: '/pages/discountsList/discountsList',
          })
        }else{
          wx.showModal({
            title: '',
            content: '尚未获取到优惠券\r\n确认进入“我的 - 优惠券”吗',
            showCancel: true,
            success: function (data) {
              console.log(data)
              if (data.confirm) {
                wx.navigateTo({
                  url: '/pages/discountsList/discountsList',
                })
              } else if (data.cancel) {
                
              }
            }
          })
        }
      },
      fail: function () {
        console.log("调用失败");
      }
    })

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 第一次获取Token
    if (!app.accesstoken) {
      this.setData({
        ModalSwitch: true
      })
      this.GetUserToken();
    } else {
      this.setData({
        ModalSwitch: false
      })
    }
  },
  // 用户信息授权按钮  
  bindGetUserInfo(e) {
    try {
      let that = this;
      var user = e.detail;
      app.userinfo.nickname = user.userInfo.nickName ? user.userInfo.nickName : '';
      app.userinfo.headimg = user.userInfo.avatarUrl;
      that.putUserData(this.codes, user.iv, user.encryptedData);
    } catch (err) { }
  },
  // 调用微信用户信息接口
  userLogin: function () {
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.codes = res.code;
        }
      },
      fail: function () { }
    })
  },
  // 获取Token，如果用户授权，直接调用微信官方WX.getUserInfo方法获取用户信息，而不是弹框授权
  GetUserToken: function () {
    var that = this;
    // 通过 wx.getSetting 先查询一下用户是否授权了 "scope.record"
    try {
      wx.getSetting({
        success(res) {
          app.hideLoadings();
          if (res.authSetting['scope.userInfo']) {
            wx.login({
              success: function (res) {
                if (res.code) {
                  // 用户首次进入小程序时，如果检测到用户已经授权，则获取新的Token
                  wx.getUserInfo({
                    success(data) {
                      app.userinfo.nickname = data.userInfo.nickName ? data.userInfo.nickName : '';
                      app.userinfo.headimg = data.userInfo.avatarUrl;
                      that.putUserData(res.code, data.iv, data.encryptedData);
                      that.setData({
                        ModalSwitch: false
                      })
                    }
                  });
                }
              },
              fail: function (err) { }
            })
          } else {
            // 未授权的解决方案 ====  调用微信获取用户信息按钮
            that.userLogin();
            app.hideLoadings();
            that.setData({
              // 页面模态框开关
              // JS模态框开关
              ModalSwitch: true,
            })
          }
        },
        complete: () => {
          app.hideLoadings();
        }
      })
    } catch (err) { }
  },

  // 授权失败模态提示框
  shouquanFail: function () {
    wx.showModal({
      title: '授权失败',
      content: '服务器繁忙，请点击页面按钮重试',
      showCancel: false,
      success: function () {
        app.hideLoadings();
      }
    })
  },

  // 发送用户数据给后台
  putUserData: function (code, IV, EncryptedData) {
    app.hideLoadings();
    let that = this;
    // Token数据请求
    wx.request({
      url: app.serviceurl + 'GetToken',
      method: "POST",
      data: {
        code: code,
        options: JSON.stringify(app.o),
        IV: IV,
        EncryptedData: EncryptedData
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.AccessToken) {
          that.setData({
            ModalSwitch: false
          })
          let resData = res.data;
          if (resData.openId !== "") {
            app.optionsToken = resData.openId;
          }
          app.HandsetNumber = resData.HandsetNumber;
          app.IsRegister = resData.IsRegister;
          app.newUser = resData.IsNewUser;
          app.accesstoken = resData.AccessToken;
          // 是否为新用户
          app.IsFresh = resData.IsFresh;
          try {
            // 将用户数据存储进本地缓存
            wx.setStorage({
              key: '_userToken',
              data: {
                HandsetNumber: resData.HandsetNumber,
                IsRegister: resData.IsRegister,
                accesstoken: resData.AccessToken,
                userDate: new Date()
              },
            });
            // 疫情包车业务二维码页面
            if (that.yiqingCode && that.touser) {
              that.toUserList();
            }
            that.checkfrom(that.op)
          } catch (err) { }
        } else {
          that.shouquanFail();
        }
      },
      fail: function () {
        try {
          that.shouquanFail();
          app.hideLoadings();
        } catch (e) { }
      },
      complete: () => {
        app.hideLoadings();
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (!app.accesstoken) {
      return that.Alert("请先点击页面授权")
    }
    return {
      title: "",
      path: `/pages/index/index?user=${app.accesstoken}&dis=true&shareid=${new Date().getTime()}`,
      imageUrl: 'https://img.hn96606.com/images/activity/fenxiang.png',
      success: function (res) {

      },
      fail(err) {
        
      }
    }
  }
})